package com.link.base.base.codereview.service;

import com.link.base.base.codereview.dao.mybatis.mapper.SysCodeReviewMapper;
import com.link.base.base.codereview.model.DirectoryTree;
import com.link.base.base.codereview.model.SysCodeReview;
import com.link.base.base.codereview.model.SysCodeReviewApproveInfo;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.database.DataSource;
import com.link.core.basic.database.DataSourceType;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.cllog.LCLogger;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 代码审核管理-专用于代码审核功能
 *
 * @author 谢鑫
 * @date 2019/09/25 09:59
 */
@Service
@DataSource(value = DataSourceType.LINKADMIN)
public class SysCodeReviewServiceImpl extends BasicServiceImpl<SysCodeReview> implements SysCodeReviewService {

    @Resource
    private SysCodeReviewMapper sysCodeReviewMapper;

    @Resource
    private SysCodeReviewApproveInfoService sysCodeReviewApproveInfoService;

    @Override
    public BasicMapper<SysCodeReview> getBasicMapper() {
        return sysCodeReviewMapper;
    }

    /**
     * 根据项目名得到目录树
     *
     * @author LiYang
     * @date 20191031
     */
    @Override
    public DirectoryTree getDirectoryTree(SysCodeReview sysCodeReview) throws Exception {
        //所有代码记录行
        List<SysCodeReview> queryList = null;
        try {
            queryList = this.queryByExamplePage(sysCodeReview);
        } catch (Exception e) {
            LCLogger.error().withMessageKey("getDirectoryTree").withMessage("根据项目查询文件列表出现异常：" + e.getMessage()).flush();
            throw new RuntimeException("根据项目查询文件列表出现异常！");
        }
        if (null == queryList || queryList.isEmpty()) {
            throw new BasicServiceException("未查询出该项目下对应文件，请检查该项目下是否包含相关文件！");
        }
        //初始化一个目录树
        DirectoryTree directoryTree = new DirectoryTree();
        //构建目录树
        generateDirectoryTree(directoryTree, queryList);
        return directoryTree;
    }

    /**
     * 生成文件目录树，暂时注释掉添加文件信息的代码，只生成树状目录结构
     *
     * @author 李杨
     * @date 2019/10/31
     */
    private void generateDirectoryTree(DirectoryTree directoryTree, List<SysCodeReview> queryList) {
        directoryTree.setDirDeep(0);
        directoryTree.setDirName("root node");
        Map<String, Object> fileMap = null;
        fileLoop : for (int i = 0; i < queryList.size(); i++) {
            SysCodeReview file = queryList.get(i);
            //构造文件fileMap
            fileMap = new HashMap<>(4);
            fileMap.put("fileName", file.getFilename());
            //得到该文件的包路径
            String packageName = file.getRootpath();
            //如果该文件没有包路径，则将该文件放在根目录下
            if (StringUtils.isBlank(packageName)) {
                //将格式化后的文件对象放入跟节点
                continue fileLoop;
            }
            //根据“.”来分路径，目前包名内容为空，换成根据rootPath字段来分，用“/”
            String[] packageNames = packageName.split("/");
            List<DirectoryTree> childrenDir = directoryTree.getChildrenDir();
            packageLoop : for (int j = 0; j < packageNames.length; j++) {
                //得到深度为j的目录名，例如深度为0的com
                String dirName = packageNames[j];

                boolean isDirExists = false;
                int existsIndex = 0;
                //查看当前节点所有子节点中是否包含该目录
                existsDirLoop : for (int k = 0; k < childrenDir.size(); k++) {
                    existsIndex = k;
                    if (dirName.equals(childrenDir.get(k).getDirName())) {
                        isDirExists = true;
                        break existsDirLoop;
                    }
                }
                if (isDirExists) {
                    if (j == packageNames.length - 1) {
                        //如果到达最大深度，则在该深度下创建文件节点
                        fileMap = new HashMap<>(4);
                        fileMap.put("fileName", file.getFilename());
                    }
                    //如果该目录已经存在，则将childrenDir赋值为当前childrenDir的子节点
                    childrenDir = childrenDir.get(existsIndex).getChildrenDir();
                } else {
                    //如果目录不存在，则使用循环开头创建的目录对象，并设置属性；创建一个目标目录
                    DirectoryTree temp = new DirectoryTree();
                    //设置目录名
                    temp.setDirName(dirName);
                    //设置这个目录在整个树结构的深度
                    temp.setDirDeep(j + 1);
                    if (j == packageNames.length - 1) {
                        //如果到达最大深度，则在该深度下创建文件节点
                        fileMap = new HashMap<>(4);
                        fileMap.put("fileName", file.getFilename());
//                        temp.getFileList().add(fileMap);
                    }
                    childrenDir.add(temp);
                    childrenDir = temp.getChildrenDir();

                }
            }
        }
    }

    /**
     * 审核接口
     *
     * @author LiYang
     * @date 2019/10/31
     * @param sysCodeReview
     * @throws Exception
     */
    @Override
    public SysCodeReview approvalCodeReview(SysCodeReview sysCodeReview) throws Exception {
        //修改代码记录的状态、审批状态等
        if (null == sysCodeReview.getId()) {
            throw new BasicServiceException("未选中需要更改状态的记录。");
        }
        //更新代码记录审核状态
        CoreUser user = UserUtil.getUser();
        sysCodeReview.setApproveDate(getDateTime());
        sysCodeReview.setApproverId(user.getId());
        sysCodeReview.setApproveName(user.getFirstName());
        Integer upReviewResult = sysCodeReviewMapper.updateStatusAndApprovalInfo(sysCodeReview);

        if (upReviewResult <= 0) {
            throw new BasicServiceException("更新代码记录审核状态失败，请检查参数是否正确。");
        }

        //新增审批记录
        SysCodeReviewApproveInfo sysCodeReviewApproveInfo = new SysCodeReviewApproveInfo();
        sysCodeReviewApproveInfo.setCodeId(sysCodeReview.getId());
        //这里暂不清楚appId的含义是什么，暂时存储审批人id（如果有的话）
        Long approvalId = sysCodeReview.getApproverId();
        if (null != approvalId) {
            sysCodeReviewApproveInfo.setAppId(sysCodeReview.getApproverId().toString());
        }
        sysCodeReviewApproveInfo.setAppName(sysCodeReview.getApproveName());
        sysCodeReviewApproveInfo.setContent(sysCodeReview.getAuditConmment());
        sysCodeReviewApproveInfo.setApprovalStatus(sysCodeReview.getStatus());
        sysCodeReviewApproveInfo.setLeader(sysCodeReview.getLeader());
        sysCodeReviewApproveInfo.setEmergencyLevel(sysCodeReview.getEmergencyLevel());
        sysCodeReviewApproveInfoService.insert(sysCodeReviewApproveInfo);
        return null;
    }

    /**
     * 通过全表的去重查询查询所有项目
     *
     * @author 李杨
     * @date 2019/10/31
     */
    @Override
    public List<SysCodeReview> queryProj(SysCodeReview sysCodeReview) throws Exception {
        return sysCodeReviewMapper.queryProj(sysCodeReview);
    }

    /**
     * 获取当前日期时间并设置 yyyy-MM-dd HH:mm:ss 格式
     *
     * @author 李杨
     * @date 2019/10/31
     */
    private String getDateTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(new Date());
    }
}

